package com.itheima.tliasmanagent.aspect;

import com.itheima.tliasmanagent.mapper.OperateLogMapper;
import com.itheima.tliasmanagent.pojo.OperateLog;
import com.itheima.tliasmanagent.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

@Slf4j
@Aspect
@Component
public class LogAspect {
    @Autowired
    private OperateLogMapper operateLogMapper;

    @Autowired
    private HttpServletRequest request;


    @Around("@annotation(com.itheima.tliasmanagent.anno.Log)")
    public Object recordLog(ProceedingJoinPoint pjp) throws Throwable {
        // 操作人ID  ---JWT中
        String jwt = request.getHeader("token");
        Claims claims = JwtUtils.parseJWT(jwt);
        Integer operateEmpId = (Integer) claims.get("id");
        // 操作时间
        LocalDateTime operatorTime = LocalDateTime.now();
        // 目标对象的类名
        String className= pjp.getTarget().getClass().getName();
        // 目标方法名
        String methodName=pjp.getSignature().getName();
        // 目标方法的参数
        Object[] args = pjp.getArgs();
        String methodParams= Arrays.toString(args);
        long begin = System.currentTimeMillis();
        // 目标方法执行的结果
        Object result = pjp.proceed();
        long end = System.currentTimeMillis();
        String returnValue = result.toString();
        // 方法执行耗时
        Long costTime=end-begin;
        OperateLog operatorLog =  new OperateLog(null,operateEmpId,operatorTime,className,methodName,methodParams,returnValue,costTime,null);
        operateLogMapper.insert(operatorLog);
        return result;
    }
}
